package org.example.service.impl;

import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.AliOSSUtils;
import org.example.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    private final String defaultImageUrl = "https://web-proj-l.oss-cn-hangzhou.aliyuncs.com/avatar/default.png";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    AliOSSUtils aliOSSUtils;

    @Override
    public User login(String name, String password) {
        User user = userMapper.getUserByName(name);
        if(user != null && user.getPassword().equals(password)) {
            return user;
        }
        else
            return null;
    }

    @Override
    public boolean register(String name, String password, MultipartFile image) {
        User user = userMapper.getUserByName(name);
        if(user!=null) {
            return false;
        }else {
            String imageUrl;
            try {
                imageUrl = CheckUtils.ImageFileInvalid(image) ? defaultImageUrl : aliOSSUtils.uploadAvatar(image);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            userMapper.addUser(name, password, imageUrl);
            return true;
        }

    }
    @Override
    public User getUserInfoById(int id) {
        return userMapper.getUserById(id);
    }
    @Override
    public boolean update(User user, MultipartFile image) {
        User u = userMapper.getUserByName(user.getName());
        if(u != null) {
            return false;
        }else {
            String imageUrl;
            try {
                if(CheckUtils.ImageFileInvalid(image))
                    imageUrl = null;
                else {
                    u = userMapper.getUserById(user.getId());
                    imageUrl = u.getImageUrl();
                    if(!imageUrl.equals(defaultImageUrl)) {
                        aliOSSUtils.deleteFile(imageUrl);
                    }
                    imageUrl = aliOSSUtils.uploadAvatar(image);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            user.setImageUrl(imageUrl);
        }
        userMapper.updateUserById(user);
        return true;
    }
    @Override
    public boolean delete(int id) {
        User u = userMapper.getUserById(id);
        String imageUrl = u.getImageUrl();
        if(!imageUrl.equals(defaultImageUrl)) {
            aliOSSUtils.deleteFile(imageUrl);
        }
        userMapper.deleteUserById(id);
        return true;
    }

}
